//
//  ViewController.m
//  WeChat
//
//  Created by 潘黎明 on 15/12/23.
//  Copyright © 2015年 潘黎明. All rights reserved.
//

#import "ViewController.h"
#import "GCDAsyncSocket.h"
@interface ViewController ()<NSStreamDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,GCDAsyncSocketDelegate>{
    NSInputStream *_inputStream;
    NSOutputStream *_outputStream;
    GCDAsyncSocket *_socket;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
@property (strong, nonatomic) NSMutableArray *msgs;
@end

@implementation ViewController
-(NSMutableArray *)msgs{
    if (_msgs == nil) {
        _msgs=[[NSMutableArray alloc]init];
    }
    return _msgs;
}
- (IBAction)connectToServer:(id)sender {
    //ios里实现socket的链接
    //1.与服务器通过三次握手建立连接
    NSString *host = @"127.0.0.1";
    int port = 12345;
    /*
    //2.定义输出流
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    //3.分配输入输出流的内存空间
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &readStream, &writeStream);
    //4.把C语言的输入输出流转换成oc对象
    _inputStream = (__bridge NSInputStream *)readStream;
    _outputStream = (__bridge NSOutputStream *)(writeStream);
    //5.设置代理
    _inputStream.delegate = self;
    _outputStream.delegate = self;
    //吧输入输出流添加到主运行循环（RunLoop）
    //主运行循环监听网络状态
    [_inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [_outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    //6.打开输入输出开关
    [_outputStream open];
    [_inputStream open];
    */
   _socket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    //链接
    NSError *error=nil;
    [_socket connectToHost:host onPort:port error:&error];
    if (error) {
        NSLog(@"%@",error);
    }
    
}
#pragma mark -socket代理
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
    //链接成功
    NSLog(@"%s",__func__);
    
}
-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    //断开连接
    if(err){
        NSLog(@"链接失败");
    }else{
        NSLog(@"正常断开");
    }
}
#pragma marke 发送数据成功
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
    [sock readDataWithTimeout:-1 tag:10001];
}
#pragma marke 读取数据
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    NSLog(@"%@",[NSThread currentThread]);
    NSString *receiveStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    if (tag == 1000) {
        
    }else if (tag = 10001){
        
    }
    
}

- (IBAction)loginbtnClick:(id)sender {
    //发送登陆请求,使用输出流
    //拼接登陆数据
    NSString *loginStr=@"im:zhangshan";
    //uint8_t * 字符数组
    //[self sendDataToHost:loginStr];
    [_socket writeData:[loginStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:1000];
    
}
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
//    NSStreamEventNone = 0,
//    NSStreamEventOpenCompleted = 1UL << 0,
//    NSStreamEventHasBytesAvailable = 1UL << 1,
//    NSStreamEventHasSpaceAvailable = 1UL << 2,
//    NSStreamEventErrorOccurred = 1UL << 3,
//    NSStreamEventEndEncountered = 1UL << 4
    switch (eventCode) {
        case NSStreamEventOpenCompleted:
            NSLog(@"建立成功");
            break;
        case NSStreamEventHasBytesAvailable:
            NSLog(@"有数据可读");
            [self readData];
            break;
        case  NSStreamEventHasSpaceAvailable:
            NSLog(@"可以发送数据");
            break;
        case NSStreamEventErrorOccurred:
            NSLog(@"错误，链接断开");
            break;
        case NSStreamEventEndEncountered:
            NSLog(@"正常的断开");
            //关掉输入输出流，从主运行循环移除
            [_inputStream close];
            [_outputStream close];
            [_inputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
            [_outputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
            break;
        default:
            break;
    }

}
-(void)readData{
    //定义缓冲区
    uint8_t buf[1024];
    //读取数据
    //length为服务器实际接收的
    NSInteger length=[_inputStream read:buf maxLength:sizeof(buf)];
    //吧缓冲区里的实现字节转换成字符串
   NSString *receiveStr = [[NSString alloc]initWithBytes:buf length:length encoding:NSUTF8StringEncoding];
    NSLog(@"%@",receiveStr);
    [self.msgs addObject:receiveStr];
    [self.tableView reloadData];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //添加键盘通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(kbWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(kbWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark 键盘将要显示
-(void)kbWillShow:(NSNotification *)not{
    //获取键盘高度
    NSLog(@"%@",not.userInfo);
    CGFloat kbHeight = [not.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    self.bottomConstraint.constant=kbHeight;
 
}

#pragma mark 键盘将要显示
-(void)kbWillHide:(NSNotification *)not{
    self.bottomConstraint.constant = 0; 
}
#pragma mark 键盘消失
//-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    [self.view endEditing:YES];
//}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
#pragma mark TextField的返回按钮
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    //发送聊天数据,有数据才发送
    NSString *text=textField.text;
    if (text.length == 0) {
        return YES;
    }
    NSString *msg=[@"msg" stringByAppendingString:text];
    [self sendDataToHost:msg];
    return YES;
}
-(void)sendDataToHost:(NSString *)msg{
    NSData *data=[msg dataUsingEncoding:NSUTF8StringEncoding];
    [_outputStream write:data.bytes maxLength:data.length];
}
#pragma marke 移除通知
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark 表格的数据源
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.msgs.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"ChatCell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.textLabel.text=self.msgs[indexPath.row];
    return cell;
}


@end
